from django.http import HttpResponse
from django.shortcuts import render
from pathlib import Path
import logging
from django.http import JsonResponse
from .日期_汇总统计数据 import query_by_date
from .时间_指令成功率图表 import  query_by_time
from .时间_车型_指令成功率图表 import query_by_time_type

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


# 确保模板文件以{% verbatim %}开头并以{% endverbatim %}结尾
def ensure_verbatim_tags(template_path):

    with open(template_path, 'r', encoding='utf-8') as f:
        content = f.read().strip()

    start_tag = '{% verbatim %}'
    end_tag = '{% endverbatim %}'

    has_start = content.startswith(start_tag)
    has_end = content.endswith(end_tag)

    if not has_start or not has_end:
        new_content = content
        if has_start:
            new_content = new_content[len(start_tag):].strip()
        if has_end:
            new_content = new_content[:-len(end_tag)].strip()

        new_content = f"{start_tag}\n{new_content}\n{end_tag}"

        with open(template_path, 'w', encoding='utf-8') as f:
            f.write(new_content)

# web开始页面
def index(request):
    ctx = {}
    # template_path = Path(__file__).resolve().parent.parent / "templates" / "command_success_analysis.html"
    # ensure_verbatim_tags(template_path)
    ctx['result_html'] = False
    return render(request, 'index3.html', ctx)



# 处理日期范围查询的视图
def query_date_type(request):
    if request.method == 'GET':
        # 获取表单参数
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        car_type = request.GET.get('car_type', '')

        # 打印日志
        logger.info(f"日期范围查询 - 开始日期: {start_date}")
        logger.info(f"日期范围查询 - 结束日期: {end_date}")
        logger.info(f"日期范围查询 - 车型: {car_type}")

        # 第一步汇总信息成query_data.xlsx
        result = query_by_date(start_date, end_date)
        print(result)
        if result:
            if car_type == 'ALL' or car_type == '':
                # 第二步:从query_data.xlsx按照search_condition查,生成html
                query_by_time('daily')
            else:
                query_by_time_type('daily', car_type)
                # 处理单车型逻辑
                pass

        template_path = Path(__file__).resolve().parent.parent / "templates" / "command_success_analysis.html"
        ensure_verbatim_tags(template_path)

        # 渲染页面（关键：传递表单参数到模板）
        ctx = {
            'result_html': True,
            'date_form_data': {
                'start_date': start_date,
                'end_date': end_date,
                'car_type': car_type
            }
        }
        return render(request, 'index3.html', ctx)

    return JsonResponse({'error': '无效请求'}, status=400)


# 处理小时范围查询的视图（修复车型参数获取）
def query_time_type(request):
    if request.method == 'GET':
        # 获取表单参数
        single_date = request.GET.get('single_date')
        start_hour = request.GET.get('start_hour')
        end_hour = request.GET.get('end_hour')
        car_type = request.GET.get('hour_car_type', '')  # 注意是hour_car_type

        # 打印日志
        logger.info(f"小时范围查询 - 查询日期: {single_date}")
        logger.info(f"小时范围查询 - 开始时间: {start_hour}")
        logger.info(f"小时范围查询 - 结束时间: {end_hour}")
        logger.info(f"小时范围查询 - 车型: {car_type}")

        # 处理查询逻辑...
        result = query_by_date(single_date, single_date)

        if result:
            if car_type == 'ALL' or car_type == '':
                # 第二步:从query_data.xlsx按照search_condition查,生成html
                query_by_time_type('hourly', car_type)
            else:
                query_by_time_type('daily', car_type)
                # 处理单车型逻辑
                pass

        template_path = Path(__file__).resolve().parent.parent / "templates" / "command_success_analysis.html"
        ensure_verbatim_tags(template_path)

        # 关键修改：传递小时表单的所有字段
        ctx = {
            'result_html': True,
            'date_form_data': {
                'single_date': single_date,
                'start_hour': start_hour,  # 正确传递开始小时
                'end_hour': end_hour,      # 正确传递结束小时
                'hour_car_type': car_type  # 传递车型（使用与前端一致的字段名）
            }
        }
        return render(request, 'index3.html', ctx)

    return JsonResponse({'error': '无效请求'}, status=400)